package com.imoresoft.magic.action;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.ambitor.grass.sql.dao.SuperDao;
import com.ambitor.grass.sql.dao.impl.SuperDaoImpl;
import com.ambitor.grass.util.data.DataMap;
import com.ambitor.grass.util.data.DatasetList;
import com.ambitor.grass.util.data.IData;
import com.ambitor.grass.util.data.IDataset;
import com.imoresoft.magic.entity.Result;
import com.imoresoft.magic.property.AppConstants;
import com.imoresoft.magic.util.DateUtil;
import com.imoresoft.magic.view.Pager;

public class UserRuleAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	private transient String ruleType;

	private IDataset userRuleSubs;

	private Result result;

	private Pager pager = new Pager();

	private transient SuperDao superDao = null;

	public UserRuleAction() throws SQLException {
		result = new Result();
		superDao = new SuperDaoImpl(pd.getConn());
	}

	public Result getResult() {
		return result;
	}

	public void setResult(Result result) {
		this.result = result;
	}

	public Pager getPager() {
		return pager;
	}

	public void setPager(Pager pager) {
		this.pager = pager;
	}

	public IDataset getUserRuleSubs() {
		if (userRuleSubs == null)
			return new DatasetList();
		return userRuleSubs;
	}

	public void setUserRuleSubs(IDataset userRuleSubs) {
		this.userRuleSubs = userRuleSubs;
	}

	public String getRuleType() {
		return ruleType;
	}

	public void setRuleType(String ruleType) {
		this.ruleType = ruleType;
	}

	@SuppressWarnings("unchecked")
	public String queryAllUserRules4Index() throws Exception {
		String ruleType = pd.getUserRuleType();
		this.setRuleType(ruleType);
		return "user_rule";
	}

	@SuppressWarnings("unchecked")
	public String forward() throws Exception {
		return pd.getUserRuleType();
	}
	
	@SuppressWarnings("unchecked")
	public String queryAllUserRules() throws Exception {
		this.setRuleType(pd.getUserRuleType());
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	public String setUserRuleValid() {
		String ruleType = pd.getRequestParameter("ruleType");
		String userId = pd.getTopUserId();
		IData param = new DataMap();
		param.put("RULE_TYPE", ruleType);
		param.put("USER_ID", userId);
		String sql1 = "update tf_m_user set rule_type = :RULE_TYPE"
				+ " where user_id=:USER_ID";
		String sql2 = "select 1 from " + ruleType + " "
				+ " where user_id = :USER_ID"
				+ " and now() between start_time and end_time";
		int count = 0;
		try {
			pd.setUserRuleType(ruleType); // 更新session里的状态
			superDao.getBaseDao().executeUpdate(sql1, param);
			count = superDao.getCount(sql2, param);
		} catch (Exception e) {
			logger.warn("", e);
			result.setCode(-1);
			result.setMsg("更新规则的过程中发生错误");
		}
		if (count == 0) {
			result.setCode(count);
			result.setMsg("当前没有生效的规则，请添加");
		}
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	public String setUserRuleInvalid() {
		String userId = pd.getTopUserId();
		IData param = new DataMap();
		param.put("USER_ID", userId);
		param.put("RULE_TYPE", StringUtils.EMPTY);
		String sql = "update tf_m_user_rule set valid_flag = 0"
				+ " where user_id=:USER_ID and rule_type = :RULE_TYPE";
		try {
			pd.setUserRuleType(StringUtils.EMPTY); // 更新session里的状态
			superDao.getBaseDao().executeUpdate(sql, param);
		} catch (Exception e) {
			logger.warn("", e);
			result.setCode(-1);
			result.setMsg("更新规则的过程中发生错误");
		}
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	public String queryUserRuleSub() {
		String ruleType = pd.getRequestParameter("ruleType");
		IData param = new DataMap();
		param.put("USER_ID", pd.getTopUserId());
		try {
			String sql = getSqlByRuleType(ruleType);
			userRuleSubs = superDao.queryListBySql(sql, param,
					pager.getFirst(), pager.getPageSize());
			pager.setTotalCount(userRuleSubs.count());
			Iterator ite = userRuleSubs.iterator();
			Map<String, String> config = getAreaConfig();
			StringBuilder areaNames = new StringBuilder();
			while (ite.hasNext()) {
				IData item = (IData) ite.next();
				Date std = (Date) item.get("START_TIME");
				Date end = (Date) item.get("END_TIME");
				Date st = (Date) item.get("S_TIME");
				Date et = (Date) item.get("E_TIME");
				item.put("VALID_FLAG", "无效");
				if (DateUtil.inPeriod(std, end))
					item.put("VALID_FLAG", "有效");
				if ("TF_M_USER_RULE_AREA".equals(ruleType)) {
					String ids = item.get("AREA_IDS").toString();
					String[] idrry = ids.split(",");
					areaNames.delete(0, areaNames.length());
					for (String id : idrry)
						areaNames.append(config.get(id) + ",");
					areaNames.deleteCharAt(areaNames.length() - 1);
					item.put("AREA_NAMES", areaNames.toString());
					areaNames.delete(0, areaNames.length());
				}
				item.put("S_TIME", DateUtil.format(st, "HH:mm"));
				item.put("E_TIME", DateUtil.format(et, "HH:mm"));
				if (end.after(DateUtil.LATEST_TIME))
					item.put("END_TIME", "不失效");
			}
		} catch (Exception e) {
			logger.error("", e);
		}
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	public Map<String, String> getAreaConfig() throws Exception {
		Object o = pd.getApplicationAttribute(AppConstants.APP_AREA_CONFIG);
		Map<String, String> areaConfig = null;
		if (o != null)
			areaConfig = (Map<String, String>) o;
		else {
			areaConfig = new HashMap<String, String>();
			IDataset provset = superDao.queryList("TD_M_PROV",
					"PROV_ID, PROV_NAME");
			Iterator ite1 = provset.iterator();
			while (ite1.hasNext()) {
				IData d1 = (IData) ite1.next();
				areaConfig.put(d1.getString("PROV_ID"), d1
						.getString("PROV_NAME"));
			}
			pd
					.setApplicationAttribute(AppConstants.APP_AREA_CONFIG,
							areaConfig);
		}

		return areaConfig;
	}

	@SuppressWarnings("unchecked")
	public String deleteUserRuleSub() {
		String ruleIds = pd.getRequestParameter("ruleIds");
		if (StringUtils.isBlank(ruleIds)) {
			result.setCode(-1);
			result.setMsg("请在下表中选择要删除的规则");
			return SUCCESS;
		}

		String[] ruleIdArray = ruleIds.split(",");
		IDataset paramList = new DatasetList();
		for (String ruleId : ruleIdArray) {
			IData param = new DataMap();
			param.put("RULE_ID", ruleId);
			paramList.add(param);
		}

		String ruleType = pd.getRequestParameter("ruleType");
		try {
			superDao.delete(ruleType, paramList);
		} catch (Exception e) {
			logger.warn("", e);
			result.setCode(-1);
			result.setMsg("删除规则的过程中发生错误");
		}

		result.setCode(1);
		return SUCCESS;
	}

	private String getSqlByRuleType(String ruleType) {
		String sql = "";
		if ("TF_M_USER_RULE_AREA".equalsIgnoreCase(ruleType)) {
			sql = "select r.START_TIME,r.END_TIME,r.RULE_ID,r.AREA_IDS,r.NUM_PER_TR,r.TITLE,s.SKIN_ID from TF_M_USER_RULE_AREA r,TF_M_USER_TEMPLET_STYLE s Where r.TEMPLET_STYLE_ID=s.TEMPLET_STYLE_ID and r.user_id=:USER_ID";
		} else if ("TF_M_USER_RULE_DATETIME".equalsIgnoreCase(ruleType)) {
			sql = "select r.START_TIME,r.END_TIME,r.START_TIME,r.END_TIME,r.RULE_ID,r.NUM_PER_TR,r.TITLE,s.SKIN_ID from TF_M_USER_RULE_DATETIME r,TF_M_USER_TEMPLET_STYLE s Where r.TEMPLET_STYLE_ID=s.TEMPLET_STYLE_ID and r.user_id=:USER_ID";
		} else if ("TF_M_USER_RULE_TIME".equalsIgnoreCase(ruleType)) {
			sql = "select r.START_TIME,r.END_TIME,r.RULE_ID,r.S_TIME,r.E_TIME,r.NUM_PER_TR,r.TITLE,s.SKIN_ID from TF_M_USER_RULE_TIME r,TF_M_USER_TEMPLET_STYLE s Where r.TEMPLET_STYLE_ID=s.TEMPLET_STYLE_ID and r.user_id=:USER_ID";
		} else if ("TF_M_USER_RULE_TEMP".equalsIgnoreCase(ruleType)) {
			sql = "select r.START_TIME,r.END_TIME,r.RULE_ID,r.START_TEMP,r.END_TEMP,r.TITLE,r.NUM_PER_TR,s.SKIN_ID from TF_M_USER_RULE_TEMP r,TF_M_USER_TEMPLET_STYLE s where r.TEMPLET_STYLE_ID=s.TEMPLET_STYLE_ID and r.user_id=:USER_ID";
		} else if ("TF_M_USER_RULE_RANDOM".equalsIgnoreCase(ruleType)) {
			sql = "select r.START_TIME,r.END_TIME,r.RULE_ID,r.TITLE,r.NUM_PER_TR,s.SKIN_ID from TF_M_USER_RULE_RANDOM r,TF_M_USER_TEMPLET_STYLE s where r.TEMPLET_STYLE_ID=s.TEMPLET_STYLE_ID and r.user_id=:USER_ID";
		}
		return sql;
	}
}
